package userLogic;

import java.sql.ResultSet;
import java.sql.SQLException;

import encryption.Encrypt;
import userService.LoginService;
import userEntity.LoginEntity;

public class LoginLogic {

    /**
     * @param login
     * @return
     * @throws Exception 
     */
	public String fetchLoginRole(LoginEntity login) throws Exception{
		String message = "";
		try{
		LoginService service = new LoginService();
		ResultSet rs = null;
			login.setPwd(Encrypt.encrypt(login.getPwd()));
			rs = service.fetchLoginRole(login);
			if(!rs.next()){
				message = "UserName/Password is incorrect";
			}
			else{
				if( rs.getBoolean("active")){
					message = rs.getString("role");
				}
				else{
					message = "Your Login is deactivated. Please contact System Admin to Re-activate";
				}
			}
			service.closeConnection();
		}
		catch(SQLException sqlException){
			sqlException.printStackTrace();
			throw sqlException;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return message;
	}

	/**
	 * @param login
	 * @throws SQLException 
	 */
	public String fetchuserName(String phNo) throws SQLException {
		ResultSet userrs = null;
		String userName = "";
		try{
			LoginService service = new LoginService();
			userrs = service.fetchUserName(phNo);
			if(userrs != null && userrs.next()){
				userName = userrs.getString("name");
			}
			else{
				throw new Exception();
			}
			service.closeConnection();
		}
		catch(SQLException sqlExep){
			sqlExep.printStackTrace();
			throw sqlExep;
		}
		catch (Exception e) {
			System.out.println("value not found in user table");
		}

		return userName;

	}

	/**
	 * @param login
	 * @return
	 * @throws SQLException 
	 */
	public String fetchPhoneNumber(LoginEntity login) throws SQLException {
		String phNo = "";
		ResultSet loginrs = null;
		try{
			LoginService service = new LoginService();
			loginrs = service.fetchUserPhoneNumber(login);
			if(loginrs != null && loginrs.next()){
				phNo = loginrs.getString("userPhoneNumber");
			}
			else{
				throw new Exception();
			}
		}
		catch(SQLException sqlExep){
			sqlExep.printStackTrace();
			throw sqlExep;
		}
		catch (Exception e) {
			System.out.println("value not found in either login table");
		}

		return phNo;
	}
	
	/**
	 * @param login
	 * @return
	 * @throws SQLException 
	 */
	public String fetchLoginId(String phoneNumber) throws SQLException
	{ 
		ResultSet rs = null;
		String loginId = "";
		try{
			LoginService service = new LoginService();
			rs = service.fetchLoginId(phoneNumber);
			if(rs != null && rs.next()){
				loginId = rs.getString("LoginId");
			}
			else{
				throw new Exception();
			}
		}
		catch(SQLException sqlExep){
			sqlExep.printStackTrace();
			throw sqlExep;
		}
		catch (Exception e) {
			System.out.println("value not found in either login table");
		}

		return loginId;
	}
}
